package com.jsjosem.aftersales.ui.worktickets;

import static com.jsjosem.aftersales.utils.CommonUtils.selectPhoto;
import static com.jsjosem.aftersales.utils.CommonUtils.showBigImg;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.ImgListViewAdapter;
import com.jsjosem.aftersales.adapter.ServiceItemsAddAdapter;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.WorkOrderApi;
import com.jsjosem.aftersales.component.CustomGridView;
import com.jsjosem.aftersales.component.ElecSignatureView;
import com.jsjosem.aftersales.data.model.Service;
import com.jsjosem.aftersales.data.request.WorkReceiptRequest;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.databinding.ActivityTicketReceiptBinding;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.request.FileRequest;
import com.jsjosem.aftersales.utils.FileUtils;
import com.jsjosem.aftersales.utils.ViewUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;
import retrofit2.Call;
import retrofit2.Retrofit;

public class TicketReceiptActivity extends AppCompatActivity {

    private Spinner spFault;
    private Spinner spProcess;
    private Spinner spServiceType;
    private EditText etFaultDesc;
    private ImageView ivAddFaultImg;
    private CustomGridView cgvFaultImgList;
    private List<String> faultImgUrls = new ArrayList<>();
    private ImgListViewAdapter imgListViewAdapter;
    private ImageView ivAddBom;
    private TableLayout tblBom;
    private TableLayout tblServiceType;
    private MaterialRatingBar rbarSatisfacation;
    private MaterialRatingBar rbarAttitude;
    private MaterialRatingBar rbarEfficiency;
    private ElecSignatureView elecSignatureView;
    private Button btClearSignature;
    private Button btConfirmSignature;
    private Button btCommit;
    private Dialog loadingDialog;
    private File signatureFile;
    private Retrofit mRetrofit;
    private String workId;
    private com.jsjosem.aftersales.databinding.ActivityTicketReceiptBinding binding;
    private ScrollView view;
    private EditText etFaultReason;
    private EditText etProcessType;
    private Context context;
    private String faultReason;
    private String processType;
    private String serviceType;
    private TableRow trServiceType;
    private TableRow trBom;
    private View scrollView;
    private String faultDesc;
    private List<Service> services;
    private ImageView serviceAdd;
    private ListView serviceList;
    private ServiceItemsAddAdapter serviceItemsAddAdapter;
    private float satisfacation;
    private float attitude;
    private float efficiency;
    private String signatureFileUploadPath;
    private final static int REQUEST_FILE_PERMISSION = 1;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ticket_receipt);
        binding = ActivityTicketReceiptBinding.inflate(getLayoutInflater());
        view = binding.getRoot();
        context = view.getContext();
        intent = getIntent();
        workId = intent.getStringExtra("workId");
        initView();
        initData();
    }

    private void initData() {
        imgListViewAdapter = new ImgListViewAdapter(this, faultImgUrls);
        cgvFaultImgList.setAdapter(imgListViewAdapter);
    }

    private void initView() {
        mRetrofit = RetrofitClient.getInstance();
        scrollView = findViewById(R.id.scrollView);
        spFault = findViewById(R.id.sp_fault_select);
        spProcess = findViewById(R.id.sp_process_select);
//        spServiceType = findViewById(R.id.sp_service_type);
        etFaultDesc = findViewById(R.id.et_fault_desc);
        ivAddFaultImg = findViewById(R.id.iv_add_fault_img);
        cgvFaultImgList = findViewById(R.id.fault_img_list);
        ivAddBom = findViewById(R.id.iv_add_bom);
        tblBom = findViewById(R.id.tbl_bom);
        tblServiceType = findViewById(R.id.tbl_service_type);
        trServiceType = findViewById(R.id.tr_service_type);
        trBom = findViewById(R.id.tr_bom);
        rbarSatisfacation = findViewById(R.id.rbar_satisfaction);
        rbarAttitude = findViewById(R.id.rbar_attitude);
        rbarEfficiency = findViewById(R.id.rbar_efficiency);
        elecSignatureView = findViewById(R.id.elec);
        btClearSignature = findViewById(R.id.bt_clear);
        btConfirmSignature = findViewById(R.id.bt_confirm);
        btCommit = findViewById(R.id.bt_commit);
        serviceAdd = findViewById(R.id.iv_service_type_add);
        serviceList = findViewById(R.id.service_lv);
        etFaultReason = findViewById(R.id.et_fault_select);
        etProcessType = findViewById(R.id.et_process_select);
//        serviceItemsAddAdapter = new ServiceItemsAddAdapter(this, services, serviceList);
//        serviceList.setAdapter(serviceItemsAddAdapter);

        // 使用签名板的时候，外部控件不滚动
        elecSignatureView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //通知父控件不要干扰,即屏蔽父控件的该事件以及该事件之后的一切action
                v.getParent().requestDisallowInterceptTouchEvent(true);
            }
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                //通知父控件不要干扰,即屏蔽父控件的该事件以及该事件之后的一切action
                v.getParent().requestDisallowInterceptTouchEvent(true);
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        });

        //选择图片
        ivAddFaultImg.setOnClickListener(view -> selectPhoto(this));

        // 删除图片
        cgvFaultImgList.setOnItemLongClickListener((adapterView, view, i, l) -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("是否删除该图片");
            builder.setPositiveButton("确定", (dialogInterface, i1) -> {
                faultImgUrls.remove(i);
                imgListViewAdapter.notifyDataSetChanged();
            });
            builder.setNegativeButton("取消", (dialogInterface, i12) -> {
            });
            builder.show();
            return true;
        });

        //图片放大
        cgvFaultImgList.setOnItemClickListener((adapterView, view, i, l) -> showBigImg(this, faultImgUrls, i));

        // 清空签名
        btClearSignature.setOnClickListener(v -> elecSignatureView.clear());

        // 确认签名
        btConfirmSignature.setOnClickListener(v -> {
            loadingShow();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_FILE_PERMISSION);
        });

        // 确认完成并回执
        btCommit.setOnClickListener(v -> {
            faultDesc = etFaultDesc.getText().toString();
            if (etFaultReason.getText().toString().isEmpty()) {
                Toast.makeText(context, "请输入故障原因后再提交", Toast.LENGTH_SHORT).show();
                return;
            } else {
                faultReason = etFaultReason.getText().toString();
            }
            if (etProcessType.getText().toString().isEmpty()) {
                Toast.makeText(context, "请输入处理方式后再提交", Toast.LENGTH_SHORT).show();
                return;
            } else {
                processType = etProcessType.getText().toString();
            }
            if (StrUtil.isBlank(faultDesc)) {
                Toast.makeText(context, "请输入故障原因后再提交", Toast.LENGTH_SHORT).show();
                return;
            }
            if (addService()) return;
            if (StrUtil.isBlank(signatureFileUploadPath)) {
                Toast.makeText(context, "请客户确认签名后再提交", Toast.LENGTH_SHORT).show();
                return;
            }
            uploadFileAndReceiptWorkOrder();
        });

        // edit点击其他地方隐藏键盘
//        ImmUtils.setCloseKeyboard(view, this);

        // 客户满意度
        rbarSatisfacation.setOnRatingChangeListener((ratingBar, rating) -> {
            satisfacation = rating;
        });

        // 服务态度
        rbarAttitude.setOnRatingChangeListener((ratingBar, rating) -> {
            attitude = rating;
        });

        // 服务效率
        rbarEfficiency.setOnRatingChangeListener((ratingBar, rating) -> {
            efficiency = rating;
        });

//        serviceAdd.setOnClickListener(v -> {
//            services.add(new Service());
//            serviceItemsAddAdapter.notifyDataSetChanged();
//            ViewUtils.setListViewHeightBasedOnChildren(serviceList);
//        });

        serviceAdd.setOnClickListener(v -> {
            tblServiceType.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
            tblServiceType.setStretchAllColumns(true);
            tblServiceType.setVisibility(View.VISIBLE);
            TableRow tableRow = new TableRow(context);
            EditText etProject = new EditText(context);
            etProject.setTextSize(12);
            etProject.setGravity(Gravity.CENTER);
            tableRow.addView(etProject);

            EditText etNumber = new EditText(context);
            etNumber.setInputType(InputType.TYPE_CLASS_NUMBER);
            etNumber.setTextSize(12);
            tableRow.addView(etNumber);

            EditText etUnit = new EditText(context);
            etUnit.setGravity(Gravity.CENTER);
            etUnit.setTextSize(12);
            tableRow.addView(etUnit);


            EditText etCost = new EditText(context);
            etCost.setInputType(InputType.TYPE_CLASS_NUMBER);
            etCost.setGravity(Gravity.CENTER);
            etCost.setTextSize(12);
            tableRow.addView(etCost);

            TextView tvDelete = new TextView(context);
            tvDelete.setTextColor(context.getResources().getColor(com.luck.picture.lib.R.color.blue));
            tvDelete.setText("删除");
            tvDelete.setTextSize(12);
            tvDelete.setGravity(Gravity.CENTER);
            tableRow.addView(tvDelete);
            tblServiceType.addView(tableRow);
            tvDelete.setOnClickListener(view -> tblServiceType.removeView(tableRow));
        });

        // TODO 添加备件
//        ivAddBom.setOnClickListener(v -> {
//        });
    }

    private boolean addService() {
        services = new ArrayList<>();
        for (int i = 0; i < tblServiceType.getChildCount(); i++) {
            TableRow row = (TableRow) tblServiceType.getChildAt(i);
            // 不要第一行
            if (i == 0) {
                continue;
            }
            // 服务项目
            TextView tvServiceProject = (TextView) row.getChildAt(0);
            String serviceProject = tvServiceProject.getText().toString();
            Service service = new Service();
            service.setName(serviceProject);

            // 数量
            EditText etNumber = (EditText) row.getChildAt(1);
            String number = etNumber.getText().toString();
            if (StrUtil.isBlank(number)) {
                Toast.makeText(context, "请填写[" + serviceProject + "]的数量", Toast.LENGTH_SHORT).show();
                return true;
            }
            service.setCount(number);

            // 单位
            EditText etUnit = (EditText) row.getChildAt(2);
            String unit = etUnit.getText().toString();
            if (StrUtil.isBlank(unit)) {
                Toast.makeText(context, "请填写[" + serviceProject + "]的单位", Toast.LENGTH_SHORT).show();
                return true;
            }
            service.setUnit(unit);

            // 费用
            EditText etCost = (EditText) row.getChildAt(2);
            String cost = etCost.getText().toString();
            if (StrUtil.isBlank(cost)) {
                Toast.makeText(context, "请填写服务项目[" + serviceProject + "]的费用", Toast.LENGTH_SHORT).show();
                return true;
            }
            service.setCost(cost);
            services.add(service);
        }
        return false;
    }

    public void loadingShow() {
        loadingDialog = new Dialog(this, R.style.normal_dialog_style);
        View loadingView = View.inflate(this, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (!hasAllPermissionsGranted(grantResults)) {
            return;
        }
        switch (requestCode) {
            case REQUEST_FILE_PERMISSION:
                signatureFile = FileUtils.bitmapToFile(elecSignatureView.getBitmap(), "signature" + System.currentTimeMillis() + ".jpeg");
                FileRequest request = new FileRequest();
                request.uploadFile(signatureFile, res -> {
                    signatureFileUploadPath = res.getData().getPath();
                    loadingDialog.dismiss();
                }, errMsg -> {
                    Toast.makeText(context, errMsg.toString(), Toast.LENGTH_SHORT).show();
                    loadingDialog.dismiss();
                });
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK && null != data) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            for (LocalMedia localMedia : selectList) {
                faultImgUrls.add(localMedia.getPath());
            }
            imgListViewAdapter.notifyDataSetChanged();
            cgvFaultImgList.setVisibility(View.VISIBLE);
        }
        if (requestCode == PictureConfig.REQUEST_CAMERA && resultCode == RESULT_OK && null != data) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            for (LocalMedia localMedia : selectList) {
                faultImgUrls.add(localMedia.getPath());
            }
            imgListViewAdapter.notifyDataSetChanged();
            cgvFaultImgList.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 上传图片并回执工单
     */
    private void uploadFileAndReceiptWorkOrder() {
        List<String> uploadImgUrls = new ArrayList<>();
        if (faultImgUrls.size() == 0) {
            Toast.makeText(this, "请选择故障图片后再回执工单", Toast.LENGTH_SHORT).show();
        } else {
            loadingShow();
            for (int i = 0; i < faultImgUrls.size(); i++) {
                File file = new File(faultImgUrls.get(i));
                FileRequest request = new FileRequest();
                int index = i;
                request.uploadFile(file, res -> {
                    uploadImgUrls.add(res.getData().getPath());
                    if (index == faultImgUrls.size() - 1) {
                        WorkOrderApi workOrderApi = mRetrofit.create(WorkOrderApi.class);
                        WorkReceiptRequest workReceiptRequest = new WorkReceiptRequest();
                        workReceiptRequest.setReason(faultReason);
                        workReceiptRequest.setProcessType(processType);
                        workReceiptRequest.setDescription(faultDesc);
                        workReceiptRequest.setServices(services);
                        workReceiptRequest.setImages(uploadImgUrls);
                        workReceiptRequest.setSignature(signatureFileUploadPath);
                        workReceiptRequest.setAttitude(String.valueOf(attitude));
                        workReceiptRequest.setEfficiency(String.valueOf(efficiency));
                        workReceiptRequest.setSatisfaction(String.valueOf(satisfacation));
                        Call<BaseResponse<Void>> receiptCall = workOrderApi.receipt(workId, workReceiptRequest);
                        AsyncRequest<BaseResponse<Void>> asyncRequest = new AsyncRequest<>();
                        asyncRequest.sendRequest(receiptCall, receiptRes -> {
                            loadingDialog.dismiss();
                            Toast.makeText(this, receiptRes.getMsg(), Toast.LENGTH_SHORT).show();
                            this.setResult(RESULT_OK, intent);
                            finish();
                        }, errMsg -> {
                            loadingDialog.dismiss();
                            Toast.makeText(this, errMsg.toString(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }, failedMessage -> {
                    loadingDialog.dismiss();
                    Toast.makeText(this, failedMessage.toString(), Toast.LENGTH_SHORT).show();
                });
            }
        }
    }
}